package top.vains.config.shiro;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.springframework.context.annotation.Configuration;
import top.vains.entity.Result;
import top.vains.util.ResultUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 权限拦截器
 *
 * @author vains
 * @version 1.0
 * @since 2020/3/19 22:52
 **/
@Slf4j
@Configuration
public class AuthorizationFilter extends PermissionsAuthorizationFilter {

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        Subject subject = this.getSubject(request, response);
        if (subject.getPrincipal() == null) {
            this.saveRequestAndRedirectToLogin(request, response);
        } else {
            response.setContentType("application/json; charset=utf-8");
            request.setCharacterEncoding("utf-8");
            PrintWriter writer = response.getWriter();
            Result result = ResultUtils.authError("权限不足，请联系管理员！");
            String valueAsString = new ObjectMapper().writeValueAsString(result);
            writer.println(valueAsString);
            writer.flush();
            writer.close();
        }
        return false;
    }
}
